//
//  TLMallMainViewController.m
//  WXReader
//
//  Created by huaya on 2025/1/10.
//  Copyright © 2025 Andrew. All rights reserved.
//

#import "TLMallMainViewController.h"
#import "TL_SearchBar.h"
#import "HMSegmentedControl.h"
#import "TLMallWaterfallFlowViewController.h"
#import "TLMallListViewController.h"

#import "TLCategoryViewController.h"
#import "TLSearchListViewController.h"

@interface TLMallMainViewController ()<UIScrollViewDelegate>

@property (nonatomic, strong) TL_BasicNavBarView *navigationBar;

@property (nonatomic, strong) HMSegmentedControl *segControl;

@property (nonatomic, strong) UIScrollView *scrollView;

@property (nonatomic, strong) NSMutableArray<UIViewController *> *viewControllers;

@property (nonatomic, strong) NSMutableArray *channelArr;

@end

@implementation TLMallMainViewController
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBar.hidden = YES;
    
}
- (NSMutableArray *)channelArr{
    if (!_channelArr) {
        _channelArr = [NSMutableArray new];
    }
    return _channelArr;
}
- (NSMutableArray<UIViewController *> *)viewControllers{
    if (!_viewControllers) {
        _viewControllers = [[NSMutableArray alloc] init];
    }
    return _viewControllers;
}
- (void)viewDidLoad {
    [self initUI];
    [self getWebPayRequest];
}
- (void)initUI{
    
    MJWeakSelf
    [TL_ViewHelper setStateBarDefaultStyle];
    
    [self.view addGradientBackground];
    
    [self.view addSubview:self.navigationBar];
    
//    TL_SearchBar *searchView = [[TL_SearchBar alloc] init];
//    searchView.searchTextField.userInteractionEnabled = NO;
//    [searchView setHiddenCancelButton];
//    searchView.searchTextField.backgroundColor = [UIColor hexF5F3FF];
//    searchView.layer.cornerRadius = 16.5;
//    searchView.layer.masksToBounds = YES;
//    searchView.placeholderText = WXLocalizedString(@"搜索书籍/作者");
//    searchView.backgroundColor = [UIColor clearColor];
//    [searchView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
//        //搜索界面
//        TLSearchListViewController *vc = [TLSearchListViewController new];
//        
//        [weakSelf.navigationController pushViewController:vc animated:YES];
//        
//    }]];
    
//    searchView.delegate = self;
    
//    [self.navigationBar addSubview:searchView];
    
//    [searchView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.equalTo(self.navigationBar).offset(kMoreHalfMargin);
//        make.right.equalTo(self.navigationBar).offset(-80);
//        make.centerY.equalTo(self.navigationBar.defaultLeftButton);
//        make.height.mas_equalTo(35.0);
//    }];
    
//   self.segControl.frame = CGRectMake(20, kStatusBarHeight+10, 240, 45);
    [self.view addSubview:self.segControl];
    [self.segControl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(10);
        make.right.equalTo(self.view.mas_right).offset(-10);
        make.height.mas_offset(45);
        make.top.equalTo(self.navigationBar.mas_bottom);
    }];
    self.segControl.indexChangeBlock = ^(NSInteger index) {
       NSInteger selectedIndex = index;
       [weakSelf setActiveViewControllerAtIndex:selectedIndex];
    };
    
    UIButton *btn = [[UIButton alloc] init];
    [btn setImage:[UIImage imageNamed:@"category"] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(categoryAction) forControlEvents:UIControlEventTouchUpInside];
    [btn setBackgroundColor:[UIColor hex_F5F3FF]];
    btn.layer.masksToBounds = YES;
    btn.layer.cornerRadius = 15;
    [self.navigationBar addSubview:btn];
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view.mas_right).offset(-16);
        make.size.mas_equalTo(CGSizeMake(30, 30));
        make.centerY.equalTo(self.navigationBar.defaultLeftButton);
    }];
    
    UIButton *btnSearch = [[UIButton alloc] init];
    [btnSearch setImage:[UIImage imageNamed:@"sy_ss"] forState:UIControlStateNormal];
    [btnSearch addTarget:self action:@selector(gotoSearchView) forControlEvents:UIControlEventTouchUpInside];
    [btnSearch setBackgroundColor:[UIColor hex_F5F3FF]];
    btnSearch.layer.masksToBounds = YES;
    btnSearch.layer.cornerRadius = 15;
    [self.navigationBar addSubview:btnSearch];
    [btnSearch mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(btn.mas_left).offset(-16);
        make.size.mas_equalTo(CGSizeMake(30, 30));
        make.centerY.equalTo(self.navigationBar.defaultLeftButton.mas_centerY);
    }];
    
    UILabel *label = [[UILabel alloc] init];
    label.frame = CGRectMake(16,55,101,29);
    label.numberOfLines = 0;
    label.text = @"TainTale";
    label.font = BOLD_SYSTEM_FONT(24);
    label.textColor = [UIColor hex_9E6DFC];
    label.textAlignment = NSTextAlignmentLeft;
    label.alpha = 1.0;
    
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:label.text];
       [attributedString addAttribute:NSObliquenessAttributeName value:@(0.2) range:NSMakeRange(0, attributedString.length)];
    label.attributedText = attributedString;
    
    [self.navigationBar addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.navigationBar).offset(kMoreHalfMargin);
        make.right.equalTo(self.navigationBar).offset(-80);
        make.centerY.equalTo(self.navigationBar.defaultLeftButton);
        make.height.mas_equalTo(30.0);
    }];
    
    
    // 配置 UIScrollView
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
    self.scrollView.pagingEnabled = YES;
    self.scrollView.delegate = self;
    self.scrollView.bounces = NO;
    self.scrollView.showsVerticalScrollIndicator = NO;
    self.scrollView.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:self.scrollView];
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.segControl.mas_bottom);
        make.bottom.equalTo(self.view.mas_bottom);
    }];
    [self.view layoutIfNeeded];
    
}
- (void)gotoSearchView{
    TLSearchListViewController *vc = [TLSearchListViewController new];
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)categoryAction{
    TLCategoryViewController *vc = [[TLCategoryViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
    
}
#pragma mark - event
- (void)setActiveViewControllerAtIndex:(NSInteger)index {
    // 更新 scrollView 的内容偏移量
    [self.scrollView setContentOffset:CGPointMake(self.view.bounds.size.width * index, 0) animated:YES];
}

#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    // 当滚动停止时更新 segment 控件
    NSInteger pageIndex = scrollView.contentOffset.x / self.view.bounds.size.width;
    self.segControl.selectedSegmentIndex = pageIndex;
}

#pragma mark - lazy load
- (TL_BasicNavBarView *)navigationBar
{
    if (!_navigationBar) {
        _navigationBar = [[TL_BasicNavBarView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, SCREEN_WIDTH, PUB_NAVBAR_HEIGHT)];
        _navigationBar.navCurrentController = self;
        _navigationBar.backgroundColor = [UIColor clearColor];
        _navigationBar.userInteractionEnabled = YES;
        [_navigationBar setSmallSeparator];
        _navigationBar.defaultLeftButton.hidden = YES;
    }
    return _navigationBar;
}
- (HMSegmentedControl *)segControl{
    if (!_segControl) {
        _segControl = [[HMSegmentedControl alloc] initWithSectionTitles:@[]];
        _segControl.backgroundColor = UIColor.clearColor;
        _segControl.titleTextAttributes = @{NSFontAttributeName : SYSTEM_FONT(16),
                                            NSForegroundColorAttributeName : [UIColor hex_666666]};
        _segControl.selectedTitleTextAttributes = @{NSFontAttributeName : BOLD_SYSTEM_FONT(18),
                                                    NSForegroundColorAttributeName : [UIColor hex_333333]};
        _segControl.selectionIndicatorHeight = 0;
        _segControl.selectionStyle = HMSegmentedControlSelectionStyleTextWidthStripe;
        _segControl.selectionIndicatorLocation = HMSegmentedControlSelectionIndicatorLocationNone;
        
        _segControl.segmentWidthStyle = HMSegmentedControlSegmentWidthStyleDynamic;
        _segControl.segmentEdgeInset = UIEdgeInsetsMake(0, 10, 0, 10);
    }
    return _segControl;
}
#pragma mark - network
- (void)getWebPayRequest {
    
//    [TL_NetworkRequestManger POST:queryChannelByColumn parameters:@{@"columnId":@"1"} model:nil success:^(BOOL isSuccess, id  _Nullable t_model, TL_NetworkRequestModel * _Nonnull requestModel) {
//        
//        if (isSuccess) {
//            
//        }
//        
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
//        
//        NSLog(@"%@",error);
//        
//    }];
    [APIManager sendGetRequest:[APIURLManager queryChannelByColumn] parameters:@{@"columnId":@"1"} model:nil success:^(BOOL success, id  _Nullable responseData, APIResponse * _Nonnull requestModel) {
        
        if (success) {

            NSArray * dataArr = requestModel.data;
            
            int i = 0;
            
            for (NSDictionary *dict in dataArr) {
//                showType 1三宫图,2瀑布流,3信息流,4banner,5模块化
                
                if (dict[@"channelName"] && ![@"" isEqualToString:dict[@"channelName"]]) {
                    [self.channelArr addObject:dict[@"channelName"]];
                    [_segControl setSectionTitles:self.channelArr];
                }
                
                if ([dict[@"showType"] isEqual:@"2"]) {
                    TLMallWaterfallFlowViewController *vc = [[TLMallWaterfallFlowViewController alloc] init];
                    vc.channelId = [dict[@"channelId"] intValue];
                    [vc resetFrame: CGRectMake(kScreenWidth*i, 0, SCREEN_WIDTH, self.scrollView.frame.size.height)];
                    [vc.view setBackgroundColor:[UIColor clearColor]];
                    [self addChildViewController:vc];
                    [self.viewControllers addObject:vc];
                    [self.scrollView addSubview:vc.view];
                }else if ([dict[@"showType"] isEqual:@"3"]) {
                    TLMallListViewController *vc = [[TLMallListViewController alloc] init];
                    vc.channelId = [dict[@"channelId"] intValue];
                    [vc resetFrame: CGRectMake(kScreenWidth*i, 0, SCREEN_WIDTH, self.scrollView.frame.size.height)];
                    [vc.view setBackgroundColor:[UIColor clearColor]];
                    [self addChildViewController:vc];
                    [self.viewControllers addObject:vc];
                    [self.scrollView addSubview:vc.view];
                }
                i++;
            }
            
            self.scrollView.contentSize = CGSizeMake(self.view.bounds.size.width * self.viewControllers.count,0);
            
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        NSLog(@"%@",error);
    }];
    
}
@end
